package org.create.builder;

import org.create.utils.IoTool;
import org.create.utils.LogTool;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

import static org.create.bean.Constants.*;


public class BuildUtils {
    private static final Map<String, String[]> packages = new HashMap<>(); // 存储包
    private static final String[] dateUtils = {"DateUtils"}; // 存储文件
    private static final String[] enums = {"DateTimePatternEnum", "PageSize", "ResponseCodeEnum"};
    private static final String[] query = {"BaseParam", "SimplePage"};
    private static final String[] mappers = {"BaseMapper"};
    private static final String[] exception = {"BusinessException"};
    private static final String[] vo = {"PaginationResultVo", "ResponseVo"};
    private static final String[] controller = {"ABaseController", "AGlobalExceptionHandlerController"};

    static {
        packages.put(PACKAGE_UTILS, dateUtils);
        packages.put(PACKAGE_ENUMS, enums);
        packages.put(PACKAGE_QUERY, query);
        packages.put(PACKAGE_MAPPERS, mappers);
        packages.put(PACKAGE_EXCEPTION, exception);
        packages.put(PACKAGE_VO, vo);
        packages.put(PACKAGE_CONTROLLER, controller);
    }

    private static void initialDir(String key) throws IOException {
        File dir;
        dir = new File(PATH_BASE_JAVA + key.replace(".", "/"));
        boolean r = dir.mkdirs();
        LogTool.printLog(r, "新建目录", dir);
        String[] files = packages.get(key);
        for (String file : files) {
            writePackage(dir, file, file, key);
        }
    }

    private static void writePackage(File dir, String resource, String target, String key) throws IOException {
        File file = new File(dir, "/" + target + JAVA_SUFFIX);
        boolean du = file.createNewFile();
        LogTool.printLog(du, "新建文件", file);

        BufferedWriter bw = IoTool.createBw(file);
        bw.write("package " + PACKAGE_BASE + "." + key + ";");

        bw.newLine();
        bw.newLine();
        IoTool.close();
        execute(resource, file);
    }

    private static void execute(String resource, File file) throws IOException {
        IoTool.copy(LOCAL_RESOURCE_PATH + resource, file, 4080, true);
    }

    public static void run() {
        try {
            for (String key : packages.keySet()) {
                initialDir(key);
            }
        } catch (Exception e) {
            LogTool.printError(e);
        }
    }

    public static void main(String[] args) {
        run();
    }
}
